<?php
/**
 * Created by PhpStorm.
 * User: huxue
 * Date: 2018/5/25
 * Time: 21:19
 */

class Pay extends M_Controller
{
    public function index(){
        $oid = $this->input->get_post('oid');
        $order =  $this->db->where('id',$oid)->get('course_order')->row_array();
        require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'/api/linepay/weixin/lib/WxPay.Api.php';
        require_once dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'/api/linepay/weixin/example/WxPay.NativePay.php';
        require_once  dirname(dirname(dirname(dirname(dirname((__FILE__))))))."/".'api/linepay/weixin/example/log.php';
        $notify = new NativePay();

        $input = new WxPayUnifiedOrder();
        $input->SetBody("购买课程");
        $input->SetAttach("test");
//        $input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOut_trade_no($order['order_no']);
        $input->SetTotal_fee($order['totalprice']*100);
//        $input->SetTotal_fee('1');
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 2592000));
        $input->SetGoods_tag("test");
//        $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
//        $input->SetNotify_url("http://47.100.228.50/api/linepay/weixin/example/notify.php");
        $input->SetNotify_url(SITE_DOMAIN."/api/linepay/weixin/example/notify.php");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];

        $this->template->assign(array('order'=>$order,'url'=>$url2));
        $this->template->display("../gw/pay.html");
    }
    //支付宝支付
    public function zfbpay(){
        require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/config.php';
        require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/pagepay/service/AlipayTradeService.php';
        require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
//        $config = dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/api/linepay/zfb/config.php';
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get("course_order")->row_array();
        //商户订单号，商户网站订单系统中唯一订单号，必填
//        $out_trade_no = trim($_POST['WIDout_trade_no']);
        $out_trade_no = $order['order_no'];

        //订单名称，必填
//        $subject = trim($_POST['WIDsubject']);
        $subject = "购买课程";

        //付款金额，必填
//        $total_amount = trim($_POST['WIDtotal_amount']);
//        $total_amount = "0.01";
        $total_amount = $order['totalprice'];

        //商品描述，可空
//        $body = trim($_POST['WIDbody']);
        $body ="k12课程";

        //构造参数
        $payRequestBuilder = new AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);

        $aop = new AlipayTradeService($config);

        /**
         * pagePay 电脑网站支付请求
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @param $return_url 同步跳转地址，公网可以访问
         * @param $notify_url 异步通知地址，公网可以访问
         * @return $response 支付宝返回的信息
         */
        $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);

        //输出表单
        var_dump($response);
    }
    public function wechatpay(){
        $oid = $this->input->get_post('oid');
        $order = $this->db->where('id',$oid)->get('course_order')->row_array();
        $this->template->assign(array('orders'=>$order));
        $this->template->display("../gw/pay_wechat.html");
    }

    public function myorder(){

        $mobile = $this->db->select('mobile')->where('id',get_cookie("user_id"))->get('user')->row_array();
//        print_r($mobile);exit;
        //获取所有订单
        $orders = $this->db->where('mobile',$mobile['mobile'])->order_by('status asc,addtime desc')->get('course_order')->result_array();
        $list = array();
        $nopay = array();
        $payList = array();
        if(count($orders)){
            foreach($orders as $order){
                $course = $this->db->where('order_id',$order['id'])->get('order_course')->result_array();
                $order['courses'] = $course;
                $list[] = $order;
                if($order['status'] == 0){
                    $order['courses'] = $course;
                    $nopay[] = $order;
                }
                if($order['status'] == 1){
                    $order['courses'] = $course;
                    $payList[] = $order;
                }
            }
        }

        $this->template->assign(array(
            'orders'=>$list,
            'nopay'=>$nopay,
            'paylist'=>$payList
        ));
        $this->template->display("../gw/my_order.html");
    }
    public function changepassword(){
        $this->template->display("../gw/change_password.html");
    }

    //选课中心
    public function electivecenter(){
        list($data, $total, $param)	= $this->_limit_page(); // 数据库中分页查询
        $id = (int)$param['id'];
        $this->template->assign(array(
            'list'=>$data,
            'total' => $total,
            'param' => $param,
            'stages'=>array("一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"),
            'subjects'=>array("语文","数学","英语","物理","化学","生物","政治","历史","地理"),
            "course_type"=>array("1V4","1V1","免费试听","公开课","专题课"),
            'auser' => $this->db->where('id', $id)->get('public_class')->row_array(),
            'pages'	=> $this->get_pagination(dr_url('admin/pay/electivecenter', array(
                'uid' => $id,
                'total' => $total,
                'search' => IS_POST ? 1 : $this->input->get('search')
            )), $total)
        ));

        $this->template->display("../gw/elective_center.html");
    }
    private function  _limit_page(){
        $page = max((int)$this->input->get_post('page'),1);
        $_total = (int)$this->input->get_post('total');

        if(!$_total){
            $this->db->where_in('course_type', array("1V4","1V1","免费试听","公开课","专题课"));
            $this->db->where('is_ground',1);
            $arr = $this->db->select("count(*) as count")->where("is_del",1)->get("public_class")->row_array();
            $_total = $arr['count'];
//            if(!$_total){
////                return array(array(), 0 ,$_param);
//                return array();
//            }
        }
        $select = $this->db;
        $_param = $this->_where($select);
        $result = $this->db
            ->limit(SITE_ADMIN_PAGESIZE, SITE_ADMIN_PAGESIZE * ($page - 1))
            ->order_by('id desc')
            ->get('public_class')
            ->result_array();
//        return array($result,$_total,$_param,$no_ground['count'],$ground['count']);
        return array($result,$_total,$_param);
    }
    private function _where(&$select) {

        $uid = (int)$this->input->get('id');
        $uid = $uid ? $uid : $this->uid;
        $search = $this->input->get('search');
        $grade = $this->input->get_post("grade");
        $subject = $this->input->get_post("subject");
        $course_type = $this->input->get_post("course_type");

        $cache_file = md5($this->duri->uri(1).$uid.$this->uid.SITE_ID.$this->input->ip_address().$this->input->user_agent()); // 缓存文件名称

        // 存在POST提交时，重新生成缓存文件
        if (IS_POST) {
            $data = $this->input->post('data');
            $this->cache->file->save($cache_file, $data, 3600);
            $search = 1;
            unset($_GET['page']);
        }
        $select->where_in('course_type', array("1V4","1V1","免费试听","公开课","专题课"));
        $select->where("is_del",1);
        $select->where('is_ground',1);
        if(isset($ground)){
            $select->where(array('is_ground'=>$ground,"is_del"=>1));
        }
        if(!empty($grade)){
            $select->where('grade', $grade);
        }
        if(!empty($subject)){
            $select->where('subject', $subject);
        }
        if(!empty($course_type)){
            $select->where('course_type', $course_type);
        }

        // 存在search参数时，读取缓存文件
        if ($search == 1) {
            $data = $this->cache->file->get($cache_file);
            if (isset($data['start']) && $data['start'] && $data['start'] != $data['end']) {
                $data['end'] = $data['end'] ? $data['end'] : SYS_TIME;
                $select->where('logintime BETWEEN '.$data['start'].' AND '. $data['end']);
            }
        }
//        $data['id'] = $uid;
        $data['grade'] = $grade;
        $data['subject'] = $subject;
        $data['course_type'] = $course_type;
        return $data;
    }

    public function electivecenterOrdercheck(){
        $course_id = $this->input->get_post("course_id");
        $course = $this->db->where("id", $course_id)->get("public_class")->row_array();
        $this->template->assign(array(
            "course"=>$course
        ));
        $this->template->display("../gw/elective_center_ordercheck.html");
    }

}
